import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/Home/index')
const Caregory = () => import('@/views/category/index')
const SubCategory = () => import('@/views/category/sub')
const Goods = () => import('@/views/goods/index')
const Login = () => import('@/views/login/index')
const Cart = () => import('@/views/cart/index')
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/', // 默认展示的二级路由组件
        name: 'Home',
        component: Home
      },
      { path: '/category/:id', component: Caregory },
      { path: '/category/sub/:id', component: SubCategory },
      { path: '/goods/:id', component: Goods },

      { path: '/cart', component: Cart },
      { path: '/member/checkout', component: () => import('@/views/member/checkout') }
    ]
  },
  { path: '/login', component: Login },
  { path: '/login/callback', component: () => import('@/views/login/callback.vue') }

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 设置前置全局路由守卫
router.beforeEach((to, from, next) => {
  // 如果当前的地址以/member开头，必须要加token
  if (to.path.startsWith('/member')) {
    // 是否有token
    if (store.state.user.profile.token) {
      next()
    } else {
      next('/login?return_url=' + to.fullPath)
    }
  } else {
    next()
  }
})

export default router
